package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 扣减库存处理器
 * @Author： wz
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

	@Autowired
	private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional
	public boolean handle(TransHandlerContext context) {
		CreateOrderContext orderContext = (CreateOrderContext) context;
		List<CartProductDto> productDtoList = orderContext.getCartProductDtoList();
		List<Long> productIds = orderContext.getBuyProductIds();
		//给buyProductIds赋值
		if (CollectionUtils.isEmpty(productIds)){
			productIds = new ArrayList<>();
			for (CartProductDto cartProductDto : productDtoList) {
				productIds.add(cartProductDto.getProductId());
			}
		}

//		List<Stock> stockList = stockMapper.findStocksForUpdate(productIds);
//		if (CollectionUtils.isEmpty(stockList)){
//			throw new BizException("库存未初始化");
//		}
//		if (stockList.size() != productIds.size()){
//			throw new BizException("部分商品未初始化");
//		}

		for (CartProductDto productDto : productDtoList) {
			Stock stock = new Stock();
			stock.setItemId(productDto.getProductId());
			stock.setLockCount(productDto.getProductNum().intValue());
			//这里的StockMapper的SQL语句可能有问题，应该是减号？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？
			stock.setStockCount(-productDto.getProductNum());
			stockMapper.updateStock(stock);
		}
		return true;
	}
}